package com.google.code.sprite.generate;

import com.google.code.sprite.util.ValidatorBuilder;
import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.HTMLWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;

import com.google.code.sprite.conf.ColumnConfig;
import com.google.code.sprite.conf.TableConfig;

public class EditPageGenerate extends AbstractGenerate {

    public String getSubPackage() {
        return tableConfig.getJavaName().toLowerCase();
    }

    public void writeToFile(TableConfig tableConfig, TableMetaData tableMetaData ) {
        init(tableConfig, tableMetaData);
        String subDir = getWebSubPackagePath();
        String fileName = FilenameUtils.concat(subDir, "edit"+entityClass+".ftl");
        String content = generate();
        content = replaceVar(content);
        writeToFile(fileName, content);
    }

    public String generate() {

        List columns=tableConfig.getColumns();
        String result="";

        SAXReader saxReader = new SAXReader();
        File file = getTemplateFile("edit-template.xhtml");
        Document document = null;
        if (!file.exists())
            return "";

        try {
            document = saxReader.read(file);
            ArrayList tables = new ArrayList();

            Element node = (Element)document.selectSingleNode("//form/input[@name='tableName']");
            //node.addAttribute("value",tableConfig.getName());

            node = (Element)document.selectSingleNode("//td[@id='tipinfo']");
            if (tableConfig.getTipInfo()!=null) node.addText(tableConfig.getTipInfo());

            node=(Element)document.selectSingleNode("//body");

            node = (Element)document.selectSingleNode("//table[@id='datatable']");


            int index=0;

            Element tr=null;
            boolean needPadTd=false;
            while (index < columns.size()) {

                ColumnConfig columnConfig=(ColumnConfig)columns.get(index++);
                String defaultValue="${" + entityVar+"." + columnConfig.getName()+"?default('')}";
                if (defaultValue==null) defaultValue="";

                if (columnConfig.getInputtype().equals("hidden")) {
                    node.addElement("input")
                        .addAttribute("type","hidden")
                        .addAttribute("name",columnConfig.getName())
                        .addAttribute("value",defaultValue);
                    node.addText(" ");
                } else {
                    tr=node.addElement("tr");

                    addInputElement(tr,columnConfig,defaultValue);
                    if (columnConfig.getColSpan()!=3) {
                        needPadTd=true;
                    }else {
                        needPadTd=false;
                    }

                    if (columnConfig.getColSpan()!=3 && index < columns.size() ) {
                        columnConfig=(ColumnConfig)columns.get(index++);
                        defaultValue="${" + entityVar+"." + columnConfig.getName()+"?default('')}";
                        if (defaultValue==null) defaultValue="";
                        addInputElement(tr,columnConfig,defaultValue);
                        needPadTd=false;
                    }
                }

            }
            if (needPadTd) {
                Element td1=tr.addElement("td")
                    .addAttribute("class","lbl")
                    .addAttribute("style","width:15%;")
                    .addAttribute("colspan","2");
            }

            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setXHTML(false);
            outformat.setExpandEmptyElements(true);

            StringWriter sw=new StringWriter();
            HTMLWriter writer = new HTMLWriter(sw, outformat);
            writer.write(document);
            writer.flush();
            writer.close();
            return sw.toString();
        }catch (Exception e ) {
            e.printStackTrace();
        }
        return null;
    }

    
	private void addInputElement(Element tr,ColumnConfig column,String  defaultValue) {
		
		String inputType=column.getInputtype();
		Element td1=tr.addElement("td")
    		.addAttribute("class","lbl")
    		.addAttribute("style","width:15%;");
		if (column.isNullable()==false)
			td1.addElement("font").addAttribute("color","red").addText("*");
		
    	td1.addText(column.getGbname());

    	Element td2=tr.addElement("td").addAttribute("class","val");
    	if (column.getColSpan()>0)  td2.addAttribute("colspan",String.valueOf(column.getColSpan()));
	
    	String gbName=column.getGbname();
    	String validator=ValidatorBuilder.getValidators(column.getType(), 
                column.isNullable(), column.isKey());
    		
		if (inputType.equals("text")) {
			Element input=td2.addElement("input")
    			.addAttribute("name",column.getName())
    			.addAttribute("value",defaultValue)
    			.addAttribute("type","text")
    			.addAttribute("class","input")
    			.addAttribute("gbname",gbName)
    			.addAttribute("validator",validator);
		 	if (column.getColSpan()>0) {
		 		input.addAttribute("size","70");
		 	} else {
		 		input.addAttribute("size","20");
		 	}
			
		}else if (inputType.equals("textarea")) {
			Element input=td2.addElement("textarea")
			.addAttribute("name",column.getName())
			.addAttribute("class","input")
			.addAttribute("rows","4")
			.addAttribute("cols","65")
			.addAttribute("gbname",gbName)
			.addAttribute("validator",validator)
			.addText(defaultValue);
			
		}else if (inputType.equals("select") || inputType.equals("selnowidth")) {
			Element input=td2.addElement("select")
			.addAttribute("name",column.getName())
			.addAttribute("type",column.getInputtype())
			.addAttribute("class","input_select")
			.addAttribute("gbname",gbName)
			.addAttribute("validator",validator);
            String selHtml ="${appsetting.getMcode('DM-ZGYZ').getHtmlTag("
                + this.entityVar + "." + column.getName() 
                + "?default(''))}";
			input.addText(selHtml);
		}else if (inputType.equals("date")) {
			Element input=td2.addElement("input")
			.addAttribute("name",column.getName())
			.addAttribute("value",defaultValue)
			.addAttribute("type","text")
			.addAttribute("class","input")
			.addAttribute("size","16")
			.addAttribute("gbname",gbName)
			.addAttribute("validator",validator);
	
			Element aHref=td2.addElement("a")
    			.addAttribute("href","javascript:void(0)")
    			.addAttribute("onClick","gfPop.fPopCalendar(document.getElementsByName('"+column.getName()+"')[0]);return false;");
			aHref.addElement("img")
				.addAttribute("name","popcal")
				.addAttribute("align","absmiddle")
				.addAttribute("src","../../../js/calendar/calbtn.gif")
				.addAttribute("border","0");
			
		}
	}
}
